﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using MyAddin;
using MySql.Data.MySqlClient;

namespace EFCodeCreater
{
    public partial class Form2 : Form
    {
        private IContainer components = null;

        private TreeView treeView1;

        private Button button1;

        private FolderBrowserDialog folderBrowserDialog1;

        public SqlConnection TrainConnection
        {
            get;
            set;
        }
        public MySqlConnection MySqlTrainConnection
        {
            get;
            set;
        }
        public string databsename
        {
            get;
            set;
        }
        public string dbtype
        {
            get;
            set;
        }
        public Form2()
        {
            this.InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            switch (dbtype)
            {
                case "sql":
                    Form2_LoadForSql();
                    break;
                case "mysql":
                    Form2_LoadForMySql();
                    break;
            }
        }

        private void Form2_LoadForSql()
        {
            string selectCommandText = "select name from sysobjects where type='U' order by name";
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectCommandText, this.TrainConnection);
            DataSet dataSet = new DataSet();
            sqlDataAdapter.Fill(dataSet, "ds1");
            foreach (DataRow dataRow in dataSet.Tables[0].Rows)
            {
                TreeNode node = new TreeNode
                {
                    Text = dataRow["name"].ToString()
                };
                this.treeView1.Nodes.Add(node);
            }
            if (File.Exists(Environment.CurrentDirectory + @"\efnamespace.txt"))
            {
                using (var sr = new StreamReader(Environment.CurrentDirectory + @"\efnamespace.txt"))
                {
                    textBox1.Text = sr.ReadToEnd();
                }
            }
            this.TrainConnection.Close();
            checkBox1.Checked = true;
        }
        private void Form2_LoadForMySql()
        {
            string selectCommandText = "select table_name  from information_schema.tables where table_schema = '" + databsename + "';";//获取所有表名
            MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(selectCommandText, MySqlTrainConnection);
            DataSet dataSet = new DataSet();
            sqlDataAdapter.Fill(dataSet, "ds1");
            foreach (DataRow dataRow in dataSet.Tables[0].Rows)
            {
                TreeNode node = new TreeNode
                {
                    Text = dataRow["table_name"].ToString()
                };
                this.treeView1.Nodes.Add(node);
            }
            if (File.Exists(Environment.CurrentDirectory + @"\efnamespace.txt"))
            {
                using (var sr = new StreamReader(Environment.CurrentDirectory + @"\efnamespace.txt"))
                {
                    textBox1.Text = sr.ReadToEnd();
                }
            }
            this.MySqlTrainConnection.Close();
            checkBox1.Checked = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show(@"请输入命名空间 例如:Company.Project.");
                return;
            }
            File.WriteAllText(Environment.CurrentDirectory + @"\efnamespace.txt", textBox1.Text);
            this.folderBrowserDialog1.ShowDialog();
            List<string> list = (from TreeNode node in this.treeView1.Nodes
                                 where node.Checked
                                 select node.Text).ToList<string>();
            CreateLogic(list, textBox1.Text);
            MessageBox.Show("生成完成");
            Application.Exit();
        }

        public void CreateLogic(List<string> list, string @namespace)
        {
            string contents = TemplateCode._name_1;
            string i_name_Service = checkBox1.Checked ? TemplateCode.I_name_Service.Replace("EntityList<_shortdtoname_DTO>", "Task<EntityList<_shortdtoname_DTO>>").Replace("void", "Task") : TemplateCode.I_name_Service;
            string name_Service = !checkBox1.Checked ? TemplateCode._name_Service.Replace("//同步_logServices", "_logServices") : TemplateCode._name_Service.Replace("EntityList<_shortdtoname_DTO>", "async Task<EntityList<_shortdtoname_DTO>>").Replace("void", "async Task").Replace("_repository.Get_shortname_List", "await _repository.Get_shortname_List").Replace("_domainServices.ModifyModel", "await _domainServices.ModifyModel").Replace("_domainServices.DelModelsById", "await _domainServices.DelModelsById").Replace(".Log", ".LogAsync").Replace("//同步_logServices", "await _logServices");
            string i_name_DomainService = !checkBox1.Checked ? TemplateCode.I_name_DomainService : TemplateCode.I_name_DomainService.Replace("void", "Task");
            string name_DomainService = !checkBox1.Checked ? TemplateCode._name_DomainService : TemplateCode._name_DomainService.Replace("void", "async Task").Replace("_repository.GetByCondition", "await _repository.GetByConditionAsync");
            string name_Repository = !checkBox1.Checked ? TemplateCode._name_Repository : TemplateCode._name_Repository.Replace("EntityList<_shortdtoname_DTO> Get_shortname_List", "async Task<EntityList<_shortdtoname_DTO>> Get_shortname_List").Replace("ToList", "ToListAsync").Replace("FindAllAsQuery", "await FindAllAsyncAsQuery").Replace("Data = DataSort", "Data = await DataSort");
            string i_name_Repository = !checkBox1.Checked ? TemplateCode.I_name_Repository : TemplateCode.I_name_Repository.Replace("EntityList<_shortdtoname_DTO>", "Task<EntityList<_shortdtoname_DTO>>");
            string efcontext = TemplateCode.efcontext;


            string dtos = TemplateCode._shortdtoname_DTO;
            string Specification = TemplateCode._specificationname_ListSpecification;
            int num = 0;
            foreach (string current in list)
            {
                string name = current;
                this.Save(contents, name, CodePath.EF_Entity.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "_name_.cs", "", 0, @namespace);
                this.Save(i_name_Service, name, CodePath.EF_IService.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "I_name_Service.cs", "", 0, @namespace);
                this.Save(name_Service, name, CodePath.EF_Service.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "_name_Service.cs", "", 0, @namespace);
                this.Save(name_Repository, name, CodePath.EF_Repository.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "_name_Repository.cs", "", 0, @namespace);
                this.Save(i_name_DomainService, name, CodePath.EF_IDomainService.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "I_name_DomainService.cs", "", 0, @namespace);
                this.Save(name_DomainService, name, CodePath.EF_DomainService.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "_name_DomainService.cs", "", 0, @namespace);
                this.Save(i_name_Repository, name, CodePath.EF_IDomainService.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "I_name_Repository.cs", "", 0, @namespace);
                this.Save(efcontext, name, CodePath.EF_OTHER, "EF基础库接入.txt", "", num, @namespace);
                this.Save(dtos, name, CodePath.EF_DTO.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "_shortdtoname_DTO.cs", "", 0, @namespace);
                this.Save(Specification, name, CodePath.EF_DomainServiceSpecification.Replace("DDD业务模块/", $"DDD业务模块/{@namespace}"), "_specificationname_ListSpecification.cs", "", 0, @namespace);
                switch (dbtype)
                {
                    case "sql":
                        this.SaveUIForSql(name, CodePath.EF_UI_Controller, @namespace);
                        break;
                    case "mysql":
                        this.SaveUIForMySql(name, CodePath.EF_UI_Controller, @namespace);
                        break;
                }

                num++;
            }
        }
        private void Save(string contents, string name, string path, string filename, string Root, int index = 0, string @namespace = "")
        {
            try
            {
                switch (dbtype)
                {
                    case "sql":
                        SaveForSql(contents, name, path, filename, Root, index, @namespace);
                        break;
                    case "mysql":
                        SaveForMySql(contents, name, path, filename, Root, index, @namespace);
                        break;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(string.IsNullOrEmpty(e.Message) ? e.InnerException == null ? e.Message : e.InnerException.Message : e.Message);
                throw;
            }

        }

        private void SaveForSql(string contents, string name, string path, string filename, string Root, int index = 0, string @namespace = "")
        {
            if (filename.Contains("_name_.cs") || filename.Contains("_shortdtoname_DTO.cs") || filename.Contains("_name_Repository.cs") || filename.Contains("_name_DomainService.cs") || filename.Contains("_name_Service.cs"))
            {
                string selectCommandText = "Select sc.name,systypes.name,sc.isnullable,sc.length,sc.prec,(select isnull(f.[value],'') from sys.columns c left join sys.extended_properties f on c.object_id = f.major_id AND f.minor_id = c.column_id where c.object_id=sc.id and c.name=sc.name) as Remark,( SELECT CASE WHEN COLUMN_NAME=sc.name THEN 1 ELSE 0 end FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='" + name + "') isPK FROM SysColumns sc inner join systypes on sc.xusertype=systypes.xusertype Where id=Object_Id('" + name + "')";
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectCommandText, this.TrainConnection);
                DataSet dataSet = new DataSet();
                sqlDataAdapter.Fill(dataSet, "ds1");
                var stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("");
                var shortBuilder = new StringBuilder();
                shortBuilder.Append("public virtual Guid ID { get; set; }\r\n\r\n");
                var repositoryBuilder = new StringBuilder();
                repositoryBuilder.Append("ID = a.ID,\r\n");
                var repositoryctypeBuilder = new StringBuilder();
                var domanmoduleupdate = new StringBuilder();
                var logcolumn = new StringBuilder();
                var def = new string[] { "ID", "IsDeleted" };
                var Ctype = new string[] { "DateTime", "bool", "DateTime?", "bool?" };
                var lastTime = "";
                foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                {
                    var len = -1;
                    string text2 = "string";
                    string text3 = dataRow[1].ToString();
                    switch (text3)
                    {
                        case "varchar":
                            len = Convert.ToInt32(dataRow[4].ToString()) > 0
                                ? Convert.ToInt32(dataRow[4].ToString())
                                : -1;
                            break;
                        case "nvarchar":
                            len = Convert.ToInt32(dataRow[4].ToString()) > 0
                                 ? Convert.ToInt32(dataRow[4].ToString())
                                 : -1;
                            break;
                        case "date":
                            text2 = "DateTime";
                            break;
                        case "time":
                            text2 = "DateTime";
                            break;
                        case "datetime2":
                            text2 = "DateTime";
                            break;
                        case "datetimeoffset":
                            text2 = "DateTime";
                            break;
                        case "tinyint":
                            text2 = "int";
                            break;
                        case "smallint":
                            text2 = "short";
                            break;
                        case "int":
                            text2 = "int";
                            break;
                        case "smalldatetime":
                            text2 = "DateTime";
                            break;
                        case "money":
                            text2 = "decimal";
                            break;
                        case "datetime":
                            text2 = "DateTime";
                            break;
                        case "float":
                            text2 = "float";
                            break;
                        case "bit":
                            text2 = "bool";
                            break;
                        case "decimal":
                            text2 = "decimal";
                            break;
                        case "numeric":
                            text2 = "int";
                            break;
                        case "smallmoney":
                            text2 = "double";
                            break;
                        case "bigint":
                            text2 = "long";
                            break;
                        case "timestamp":
                            text2 = "int";
                            break;
                        case "uniqueidentifier":
                            text2 = "Guid";
                            break;

                    }
                    if (text2 != "string" && dataRow[2].ToString() == "1")
                    {
                        text2 += "?";
                    }
                    stringBuilder.Append("        /// <summary>\r\n");
                    stringBuilder.Append("        /// " + dataRow[5] + "\r\n");
                    stringBuilder.Append("        /// </summary>\r\n");
                    stringBuilder.Append("        [DisplayName(@\"" + dataRow[5] + "\")]\r\n");
                    if (len > 0)
                    {
                        stringBuilder.Append("        [MaxLength(" + len + ")]\r\n");
                    }
                    if (dataRow[6].ToString() == "1")
                        stringBuilder.Append("        [Key]\r\n");
                    stringBuilder.Append(string.Concat(new object[]
                    {
                        "        public ",
                        text2,
                        " ",
                        dataRow[0],
                        " { get; set; }\r\n\r\n"
                    }));
                    if (!def.Contains(dataRow[0]))
                    {
                        if ("CreateTime" != dataRow[0].ToString())
                        {
                            shortBuilder.Append("        /// <summary>\r\n");
                            shortBuilder.Append("        /// " + dataRow[5] + "\r\n");
                            shortBuilder.Append("        /// </summary>\r\n");
                            shortBuilder.Append("        [DisplayName(@\"" + dataRow[5] + "\")]\r\n");
                            if (Ctype.Contains(text2))
                            {
                                shortBuilder.Append("        [JqGridColumnOpt(sortName:@\"" + dataRow[0] + "\")]\r\n");
                                switch (text2)
                                {
                                    case "DateTime":
                                        repositoryctypeBuilder.Append("		        x." + dataRow[0] + "Str" + " = x." + dataRow[0] +
                                                                 ".ToString(\"yyyy-MM-dd\");\r\n");
                                        break;
                                    case "DateTime?":
                                        repositoryctypeBuilder.Append("		        x." + dataRow[0] + "Str" + " = x." + dataRow[0] +
                                                               "?.ToString(\"yyyy-MM-dd\");\r\n");
                                        break;
                                    case "bool":
                                        repositoryctypeBuilder.Append("		        x." + dataRow[0] + "Str" + " = x." + dataRow[0] + " ? \"是\" : \"否\";\r\n");
                                        break;
                                    case "bool?":
                                        repositoryctypeBuilder.Append("		        x." + dataRow[0] + "Str" + " = x." + dataRow[0] + " == null ? \"\" : x." + dataRow[0] + " == true ? \"是\" : \"否\";\r\n");
                                        break;
                                }
                                if (text2 == "DateTime")
                                {

                                }
                                else if (text2 == "bool")
                                {

                                }
                            }
                            if (dataRow[6].ToString() == "1")
                                shortBuilder.Append("        [Key]\r\n");
                            if (Ctype.Contains(text2))
                            {

                                shortBuilder.Append(string.Concat(new object[]
                                {
                                    "        public ",
                                    "string",
                                    " ",
                                    dataRow[0] + "Str",
                                    " { get; set; }\r\n\r\n"
                                }));
                                shortBuilder.Append(string.Concat(new object[]
                                {
                                    "        public virtual ",
                                    text2,
                                    " ",
                                    dataRow[0],
                                    " { get; set; }\r\n\r\n"
                                }));
                            }
                            else
                            {
                                shortBuilder.Append(string.Concat(new object[]
                                {
                                    "        public ",
                                    text2,
                                    " ",
                                    dataRow[0],
                                    " { get; set; }\r\n\r\n"
                                }));
                            }

                            domanmoduleupdate.Append("x => x." + dataRow[0] + ", ");
                            if (text2 != "Guid")
                            {
                                logcolumn.Append(dataRow[5] + "=[{item." + dataRow[0] + "}],");
                            }
                        }
                        else
                        {
                            shortBuilder.Append(string.Concat(new object[]
                            {
                                "        public virtual ",
                                text2,
                                " ",
                                dataRow[0],
                                " { get; set; }\r\n\r\n"
                            }));
                        }
                        repositoryBuilder.Append("                    " + dataRow[0] + " = " + "a." + dataRow[0] +
                                                 ",\r\n");
                    }
                }
                if (filename.Contains("_shortdtoname_DTO.cs"))
                {
                    contents = contents.Replace("_foreach_", shortBuilder.ToString());
                }
                else if (filename.Contains("_name_.cs"))
                {
                    contents = contents.Replace("_foreach_", stringBuilder.ToString());
                }
                else if (filename.Contains("_name_DomainService.cs"))
                {
                    var domanupstr = domanmoduleupdate.ToString();
                    domanupstr = domanupstr.Substring(0, domanupstr.Length - 2);
                    contents = contents.Replace("_updateforeach_", domanupstr);
                }
                else if (filename.Contains("_name_Service.cs"))
                {
                    var pjname = @namespace.Substring(@namespace.IndexOf('.'),
                        @namespace.Length - @namespace.IndexOf('.')).Replace(".", "");
                    contents = contents
                        .Replace("IPJT_Manager_LogServices", "I" + pjname + "_Manager_LogServices");
                    if (!string.IsNullOrEmpty(logcolumn.ToString()))
                    {
                        contents = contents.Replace("_logcolumn_",
                            logcolumn.ToString().Substring(0, logcolumn.Length - 1));
                    }
                }
                else if (filename.Contains("_name_Repository.cs"))
                {
                    var str = repositoryBuilder.ToString();
                    str = str.Substring(0, str.Length - 3);
                    var ctype = "";
                    if (repositoryctypeBuilder.Length > 0)
                    {
                        ctype += "result.Data.ForEach(x =>\r\n		    {\r\n" + repositoryctypeBuilder + "		    });";
                    }
                    contents = contents.Replace("_foreach_", str).Replace("_ctypeForeach_", ctype);
                }
            }
            var shortname = name.Substring(name.LastIndexOf("_") + 1, name.Length - 1 - name.LastIndexOf("_"));
            var shordtotname = "";
            var specificationname = shordtotname =
                name.Substring(name.IndexOf("_") + 1, name.Length - 1 - name.IndexOf("_")).Replace("_", "");
            var middleName = name.Split('_')[1];
            var cpname = @namespace.Substring(0, @namespace.IndexOf('.')).Replace(".", "");
            contents = contents.Replace("_name_", name).Replace("_shortname_", shortname).Replace("_specificationname_", specificationname).Replace("_shortdtoname_", shordtotname);
            contents = contents.Replace("Domain.Model", @namespace + "Domain.Model")
                .Replace("Domain.MainModule", @namespace + "Domain.MainModule")
                .Replace("Infrastructure.Repository", @namespace + "Infrastructure.Repository")
                .Replace("Application.Service", @namespace + "Application.Service")
                .Replace("Infrastructure.Common", @namespace + "Infrastructure.Common")
                .Replace("Domain.Base", @namespace + "Domain.Base")//更换命名空间
              
                .Replace("Application.BaseService", @namespace + "Application.BaseService")
                .Replace("Utility", cpname + ".Utility");
            path += (filename.Contains("依赖注入") || filename.Contains("EF基础库接入") ? "" : (filename == ("_name_Repository.cs") || filename == ("_name_DomainService.cs") || filename == ("_name_Service.cs") ? "MainModule" : "") + "/" + middleName + "/");
            string path2 = this.folderBrowserDialog1.SelectedPath + path + filename.Replace("_name_", name).Replace("_shortname_", shortname).Replace("_specificationname_", specificationname).Replace("_shortdtoname_", shordtotname);
            Directory.CreateDirectory(this.folderBrowserDialog1.SelectedPath + path);
            if (filename.Contains("依赖注入") || filename.Contains("EF基础库接入"))
            {
                if (index == 0)
                {
                    File.WriteAllText(path2, filename.Replace(".txt", "") + "\r\n" + contents);
                }
                else
                {
                    File.AppendAllText(path2, "\r\n" + contents);
                }
            }
            else
            {
                File.WriteAllText(path2, contents);
            }
        }
        private void SaveForMySql(string contents, string name, string path, string filename, string Root, int index = 0, string @namespace = "")
        {
            if (filename.Contains("_name_.cs") || filename.Contains("_shortdtoname_DTO.cs") || filename.Contains("_name_Repository.cs") || filename.Contains("_name_DomainService.cs") || filename.Contains("_name_Service.cs"))
            {
                string selectCommandText = @"select column_name as name,data_type as type,COLUMN_TYPE as cloumtype,IS_NULLABLE as isnull,column_comment as remork,
                    (SELECT  CASE WHEN column_name = b.column_name THEN 1 ELSE 0 end FROM INFORMATION_SCHEMA.`KEY_COLUMN_USAGE`  WHERE table_name = 'kiidfx_manager_baseinfo' AND CONSTRAINT_SCHEMA = 'kiidfx_main'  AND constraint_name = 'PRIMARY') as ispk
                    from information_schema.columns as b where table_schema = '" + databsename + "' and table_name = '" + name + "'; ";
                MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(selectCommandText, MySqlTrainConnection);
                DataSet dataSet = new DataSet();
                sqlDataAdapter.Fill(dataSet, "ds1");
                var stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("");
                var shortBuilder = new StringBuilder();
                shortBuilder.Append("public virtual Guid ID { get; set; }\r\n\r\n");
                var repositoryBuilder = new StringBuilder();
                repositoryBuilder.Append("ID = a.ID,\r\n");
                var repositoryctypeBuilder = new StringBuilder();
                var domanmoduleupdate = new StringBuilder();
                var logcolumn = new StringBuilder();
                var def = new string[] { "ID", "IsDeleted" };
                var Ctype = new string[] { "DateTime", "bool", "DateTime?", "bool?" };
                var lastTime = "";
                foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                {
                    var len = -1;
                    string text2 = "string";
                    string text3 = dataRow["type"].ToString();
                    switch (text3)
                    {
                        case "varchar":
                            //处理mysql字段长度问题
                            var cloumtype = dataRow["cloumtype"].ToString();
                            var mach = Regex.Match(cloumtype, @"\(.*?\)");
                            if (mach != null && !string.IsNullOrEmpty(mach.Value))
                            {
                                var machval = mach.Value.ToString();
                                len = Convert.ToInt32(machval.Substring(1, machval.LastIndexOf(")", StringComparison.Ordinal) - 1));
                            }
                            if (len == 36)//处理mysql guid
                            {
                                len = 0;
                                text2 = "Guid";
                            }
                            break;
                        case "nvarchar":
                            //处理mysql字段长度问题
                            cloumtype = dataRow["cloumtype"].ToString();
                            mach = Regex.Match(cloumtype, @"\(.*?\)");
                            if (mach != null && !string.IsNullOrEmpty(mach.Value))
                            {
                                var machval = mach.Value.ToString();
                                len = Convert.ToInt32(machval.Substring(1, machval.LastIndexOf(")", StringComparison.Ordinal) - 1));
                            }

                            if (len == 36)//处理mysql guid
                            {
                                len = 0;
                                text2 = "Guid";
                            }
                            break;
                        case "date":
                            text2 = "DateTime";
                            break;
                        case "time":
                            text2 = "DateTime";
                            break;
                        case "datetime2":
                            text2 = "DateTime";
                            break;
                        case "datetimeoffset":
                            text2 = "DateTime";
                            break;
                        case "tinyint":
                            text2 = "int";
                            break;
                        case "smallint":
                            text2 = "short";
                            break;
                        case "int":
                            text2 = "int";
                            break;
                        case "smalldatetime":
                            text2 = "DateTime";
                            break;
                        case "money":
                            text2 = "decimal";
                            break;
                        case "datetime":
                            text2 = "DateTime";
                            break;
                        case "float":
                            text2 = "float";
                            break;
                        case "bit":
                            text2 = "bool";
                            break;
                        case "decimal":
                            text2 = "decimal";
                            break;
                        case "numeric":
                            text2 = "int";
                            break;
                        case "smallmoney":
                            text2 = "double";
                            break;
                        case "bigint":
                            text2 = "long";
                            break;
                        case "timestamp":
                            text2 = "int";
                            break;
                        case "uniqueidentifier":
                            text2 = "Guid";
                            break;

                    }
                    if (text2 != "string" && dataRow["isnull"].ToString() == "YES")
                    {
                        text2 += "?";
                    }
                    stringBuilder.Append("        /// <summary>\r\n");
                    stringBuilder.Append("        /// " + dataRow["remork"] + "\r\n");
                    stringBuilder.Append("        /// </summary>\r\n");
                    stringBuilder.Append("        [DisplayName(@\"" + dataRow["remork"] + "\")]\r\n");
                    if (len > 0)
                    {
                        stringBuilder.Append("        [MaxLength(" + len + ")]\r\n");
                    }
                    if (dataRow["ispk"].ToString() == "1")
                        stringBuilder.Append("        [Key]\r\n");
                    stringBuilder.Append(string.Concat(new object[]
                    {
                        "        public ",
                        text2,
                        " ",
                        dataRow["name"],
                        " { get; set; }\r\n\r\n"
                    }));
                    if (!def.Contains(dataRow["name"]))
                    {
                        if ("CreateTime" != dataRow["name"].ToString())
                        {
                            shortBuilder.Append("        /// <summary>\r\n");
                            shortBuilder.Append("        /// " + dataRow["remork"] + "\r\n");
                            shortBuilder.Append("        /// </summary>\r\n");
                            shortBuilder.Append("        [DisplayName(@\"" + dataRow["remork"] + "\")]\r\n");
                            if (Ctype.Contains(text2))
                            {
                                shortBuilder.Append("        [JqGridColumnOpt(sortName:@\"" + dataRow["name"] + "\")]\r\n");
                                switch (text2)
                                {
                                    case "DateTime":
                                        repositoryctypeBuilder.Append("		        x." + dataRow["name"] + "Str" + " = x." + dataRow["name"] +
                                                                 ".ToString(\"yyyy-MM-dd\");\r\n");
                                        break;
                                    case "DateTime?":
                                        repositoryctypeBuilder.Append("		        x." + dataRow["name"] + "Str" + " = x." + dataRow["name"] +
                                                               "?.ToString(\"yyyy-MM-dd\");\r\n");
                                        break;
                                    case "bool":
                                        repositoryctypeBuilder.Append("		        x." + dataRow["name"] + "Str" + " = x." + dataRow["name"] + " ? \"是\" : \"否\";\r\n");
                                        break;
                                    case "bool?":
                                        repositoryctypeBuilder.Append("		        x." + dataRow["name"] + "Str" + " = x." + dataRow["name"] + " == null ? \"\" : x." + dataRow["name"] + " == true ? \"是\" : \"否\";\r\n");
                                        break;
                                }
                                if (text2 == "DateTime")
                                {

                                }
                                else if (text2 == "bool")
                                {

                                }
                            }
                            if (dataRow["ispk"].ToString() == "1")
                                shortBuilder.Append("        [Key]\r\n");
                            if (Ctype.Contains(text2))
                            {

                                shortBuilder.Append(string.Concat(new object[]
                                {
                                    "        public ",
                                    "string",
                                    " ",
                                    dataRow["name"] + "Str",
                                    " { get; set; }\r\n\r\n"
                                }));
                                shortBuilder.Append(string.Concat(new object[]
                                {
                                    "        public virtual ",
                                    text2,
                                    " ",
                                    dataRow["name"],
                                    " { get; set; }\r\n\r\n"
                                }));
                            }
                            else
                            {
                                shortBuilder.Append(string.Concat(new object[]
                                {
                                    "        public ",
                                    text2,
                                    " ",
                                    dataRow["name"],
                                    " { get; set; }\r\n\r\n"
                                }));
                            }

                            domanmoduleupdate.Append("x => x." + dataRow["name"] + ", ");
                            if (text2 != "Guid")
                            {
                                logcolumn.Append(dataRow["remork"] + "=[{item." + dataRow["name"] + "}],");
                            }
                        }
                        else
                        {
                            shortBuilder.Append(string.Concat(new object[]
                            {
                                "        public virtual ",
                                text2,
                                " ",
                                dataRow["name"],
                                " { get; set; }\r\n\r\n"
                            }));
                        }
                        repositoryBuilder.Append("                    " + dataRow["name"] + " = " + "a." + dataRow["name"] +
                                                 ",\r\n");
                    }
                }
                if (filename.Contains("_shortdtoname_DTO.cs"))
                {
                    contents = contents.Replace("_foreach_", shortBuilder.ToString());
                }
                else if (filename.Contains("_name_.cs"))
                {
                    contents = contents.Replace("_foreach_", stringBuilder.ToString());
                }
                else if (filename.Contains("_name_DomainService.cs"))
                {
                    var domanupstr = domanmoduleupdate.ToString();
                    domanupstr = domanupstr.Substring(0, domanupstr.Length - 2);
                    contents = contents.Replace("_updateforeach_", domanupstr);
                }
                else if (filename.Contains("_name_Service.cs"))
                {
                    var pjname = @namespace.Substring(@namespace.IndexOf('.'),
                        @namespace.Length - @namespace.IndexOf('.')).Replace(".", "");
                    contents = contents
                        .Replace("IPJT_Manager_LogServices", "I" + pjname + "_Manager_LogServices");
                    if (!string.IsNullOrEmpty(logcolumn.ToString()))
                    {
                        contents = contents.Replace("_logcolumn_",
                            logcolumn.ToString().Substring(0, logcolumn.Length - 1));
                    }
                }
                else if (filename.Contains("_name_Repository.cs"))
                {
                    var str = repositoryBuilder.ToString();
                    str = str.Substring(0, str.Length - 3);
                    var ctype = "";
                    if (repositoryctypeBuilder.Length > 0)
                    {
                        ctype += "result.Data.ForEach(x =>\r\n		    {\r\n" + repositoryctypeBuilder + "		    });";
                    }
                    contents = contents.Replace("_foreach_", str).Replace("_ctypeForeach_", ctype);
                }
            }
            var shortname = name.Substring(name.LastIndexOf("_") + 1, name.Length - 1 - name.LastIndexOf("_"));
            var shordtotname = "";
            var specificationname = shordtotname =
                name.Substring(name.IndexOf("_") + 1, name.Length - 1 - name.IndexOf("_")).Replace("_", "");
            var middleName = name.Split('_')[1];
            var cpname = @namespace.Substring(0, @namespace.IndexOf('.')).Replace(".", "");
            contents = contents.Replace("_name_", name).Replace("_shortname_", shortname).Replace("_specificationname_", specificationname).Replace("_shortdtoname_", shordtotname);
            contents = contents.Replace("Domain.Model", @namespace + "Domain.Model")
                .Replace("Domain.MainModule", @namespace + "Domain.MainModule")
                .Replace("Infrastructure.Repository.Sqlserver", @namespace + "Infrastructure.Repository.Sqlserver")
                .Replace("Application.Service", @namespace + "Application.Service")
                .Replace("Infrastructure.Common", @namespace + "Infrastructure.Common");
            path += (filename.Contains("依赖注入") || filename.Contains("EF基础库接入") ? "" : (filename == ("_name_Repository.cs") || filename == ("_name_DomainService.cs") || filename == ("_name_Service.cs") ? "MainModule" : "") + "/" + middleName + "/");
            string path2 = this.folderBrowserDialog1.SelectedPath + path + filename.Replace("_name_", name).Replace("_shortname_", shortname).Replace("_specificationname_", specificationname).Replace("_shortdtoname_", shordtotname);
            Directory.CreateDirectory(this.folderBrowserDialog1.SelectedPath + path);
            if (filename.Contains("依赖注入") || filename.Contains("EF基础库接入"))
            {
                if (index == 0)
                {
                    File.WriteAllText(path2, filename.Replace(".txt", "") + "\r\n" + contents);
                }
                else
                {
                    File.AppendAllText(path2, "\r\n" + contents);
                }
            }
            else
            {
                File.WriteAllText(path2, contents);
            }
        }
        private void SaveUIForSql(string name, string path, string @namespace = "")
        {
            string selectCommandText = "Select sc.name,systypes.name,sc.isnullable,sc.length,sc.prec,(select isnull(f.[value],'') from sys.columns c left join sys.extended_properties f on c.object_id = f.major_id AND f.minor_id = c.column_id where c.object_id=sc.id and c.name=sc.name) as Remark,( SELECT CASE WHEN COLUMN_NAME=sc.name THEN 1 ELSE 0 end FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='" + name + "') isPK FROM SysColumns sc inner join systypes on sc.xusertype=systypes.xusertype Where id=Object_Id('" + name + "')";
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectCommandText, this.TrainConnection);
            DataSet dataSet = new DataSet();
            sqlDataAdapter.Fill(dataSet, "ds1");
            var action = UITemplateCode.controller_action;
            var detailview = UITemplateCode._name_detail_cshtml;
            var detailjs = UITemplateCode._name_detail_js;
            var listview = UITemplateCode._name_list_cshtml;
            var listjs = UITemplateCode._name_list_js;
            var eachtxt = LoadUItxt(dataSet.Tables[0].Rows, out var dateload);
            SaveUIFile(name, checkBox1.Checked, action, eachtxt, dateload, path, "_name_控制器.txt", @namespace);
            SaveUIFile(name, checkBox1.Checked, detailview, eachtxt, dateload, path, "_name_Detail.cshtml", @namespace);
            SaveUIFile(name, checkBox1.Checked, detailjs, eachtxt, dateload, path, "_name_Detail.js", @namespace);
            SaveUIFile(name, checkBox1.Checked, listview, eachtxt, dateload, path, "_name_.cshtml", @namespace/*, LoadcolModelList(dataSet.Tables[0].Rows)*/);
            SaveUIFile(name, checkBox1.Checked, listjs, eachtxt, dateload, path, "_name_.js", @namespace);
        }
        private void SaveUIForMySql(string name, string path, string @namespace = "")
        {
            string selectCommandText = @"select column_name as name,data_type as type,COLUMN_TYPE as cloumtype,IS_NULLABLE as isnull,column_comment as remork,
                    (SELECT  CASE WHEN column_name = b.column_name THEN 1 ELSE 0 end FROM INFORMATION_SCHEMA.`KEY_COLUMN_USAGE`  WHERE table_name = 'kiidfx_manager_baseinfo' AND CONSTRAINT_SCHEMA = 'kiidfx_main'  AND constraint_name = 'PRIMARY') as ispk
                    from information_schema.columns as b where table_schema = '" + databsename + "' and table_name = '" + name + "'; ";
            MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(selectCommandText, MySqlTrainConnection);
            DataSet dataSet = new DataSet();
            sqlDataAdapter.Fill(dataSet, "ds1");
            var action = UITemplateCode.controller_action;
            var detailview = UITemplateCode._name_detail_cshtml;
            var detailjs = UITemplateCode._name_detail_js;
            var listview = UITemplateCode._name_list_cshtml;
            var listjs = UITemplateCode._name_list_js;
            var eachtxt = LoadUItxt(dataSet.Tables[0].Rows, out var dateload);
            SaveUIFile(name, checkBox1.Checked, action, eachtxt, dateload, path, "控制器.txt", @namespace);
            SaveUIFile(name, checkBox1.Checked, detailview, eachtxt, dateload, path, "_name_Detail.cshtml", @namespace);
            SaveUIFile(name, checkBox1.Checked, detailjs, eachtxt, dateload, path, "_name_Detail.js", @namespace);
            SaveUIFile(name, checkBox1.Checked, listview, eachtxt, dateload, path, "_name_.cshtml", @namespace/*, LoadcolModelList(dataSet.Tables[0].Rows)*/);
            SaveUIFile(name, checkBox1.Checked, listjs, eachtxt, dateload, path, "_name_.js", @namespace);
        }

        void SaveUIFile(string modelName, bool isTask, string file, string eachtxt, string dateload, string fileDir, string filename, string @namespace, string LoadcolModelList = null)
        {
            dynamic tCode = new ExpandoObject();
            tCode.name = modelName.Split('_')[2];
            tCode.model = modelName;
            tCode.services = "_" + modelName.Split('_')[2].ToLower() + "Services";
            tCode.chinaname = modelName.Split('_')[2] + "管理";
            tCode.controller = modelName.Split('_')[1];
            tCode.areaName = "Admin";
            tCode.@namespace = @namespace;
            var enumload = "";
            StringBuilder sb = new StringBuilder(file);
            if (isTask)
            {
                sb = sb.Replace("ActionResult Edit", "async Task<IActionResult> Edit")
                    .Replace("ActionResult Save", "async Task<IActionResult> Save")
                    .Replace("ActionResult Get", "async Task<IActionResult> Get")
                    .Replace("ActionResult Del", "async Task<IActionResult> Del")
                    .Replace("_services_.Get_name_List(page, rows, sort, export)", "(_services_.Get_name_List(page, rows, sort, export))")
                    .Replace("_services_", "await _services_")
                    .Replace("LogicDelete", "LogicDeleteAsync")
                    .Replace("_logServices.Log", "await _logServices.LogAsync")
                    .Replace("GetByKey", "GetByKeyAsync")
                    .Replace("result.RunWithTry(x =>", "await result.RunWithAsyncTry(async x =>");
            }
            var newsb = sb.Replace("_modellist_", string.IsNullOrEmpty(LoadcolModelList) ? "" : LoadcolModelList).Replace("_name_", tCode.name).Replace("_shortname_", tCode.model.Substring(tCode.model.IndexOf("_") + 1, tCode.model.Length - 1 - tCode.model.IndexOf("_")).Replace("_", ""))
                .Replace("_services_", tCode.services)
                .Replace("_model_", tCode.model)
                .Replace("_中文_", tCode.chinaname)
                .Replace("_controller_", tCode.controller)
                .Replace("_areaName_", tCode.areaName).Replace("_foreach_", eachtxt.Replace("_controller_", tCode.controller)
                .Replace("_areaName_", tCode.areaName)).Replace("_enumload_", enumload).Replace("_dateload_", dateload).Replace("using Domain.Model", "using " + tCode.@namespace + "Domain.Model");
            var name = filename.Replace("_name_", tCode.name);
            if (!Directory.Exists(this.folderBrowserDialog1.SelectedPath + fileDir))
            {
                Directory.CreateDirectory(this.folderBrowserDialog1.SelectedPath + fileDir);
            }
            File.WriteAllText(this.folderBrowserDialog1.SelectedPath + fileDir + name, newsb.ToString(), Encoding.UTF8);
        }

        public static string LoadUItxt(DataRowCollection drs, out string dateloads)
        {
            string areaname = "Admin";
            StringBuilder sb = new StringBuilder();
            dateloads = "";
            try
            {
                var def = new string[] { "ID", "IsDeleted", "CreateTime" };
                var columns = new List<DataCoulmnDTO>();
                foreach (DataRow dataRow in drs)
                {
                    var text2 = typeof(string);
                    string text3 = dataRow[1].ToString();
                    var len = -1;
                    switch (text3)
                    {
                        case "varchar":
                            len = Convert.ToInt32(dataRow[4].ToString()) > 0
                                ? Convert.ToInt32(dataRow[4].ToString())
                                : -1;
                            len = len / 2;//若是varchar,则最大长度取中文字符
                            break;
                        case "nvarchar":
                            len = Convert.ToInt32(dataRow[4].ToString()) > 0
                                 ? Convert.ToInt32(dataRow[4].ToString())
                                 : -1;
                            break;
                        case "date":
                            text2 = typeof(DateTime);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(DateTime?);
                            }
                            break;
                        case "time":
                            text2 = typeof(TimeSpan);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(TimeSpan?);
                            }
                            break;
                        case "datetime2":
                            text2 = typeof(DateTime);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(TimeSpan?);
                            }
                            break;
                        case "datetimeoffset":
                            text2 = typeof(DateTime);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(TimeSpan?);
                            }
                            break;
                        case "tinyint":
                            text2 = typeof(int);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(int?);
                            }
                            break;
                        case "smallint":
                            text2 = typeof(short);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(short?);
                            }
                            break;
                        case "int":
                            text2 = typeof(int);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(int?);
                            }
                            break;
                        case "smalldatetime":
                            text2 = typeof(TimeSpan);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(TimeSpan?);
                            }
                            break;
                        case "money":
                            text2 = typeof(decimal);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(decimal?);
                            }
                            break;
                        case "datetime":
                            text2 = typeof(DateTime);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(TimeSpan?);
                            }
                            break;
                        case "float":
                            text2 = typeof(float);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(float?);
                            }
                            break;
                        case "bit":
                            text2 = typeof(bool);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(bool?);
                            }
                            break;
                        case "decimal":
                            text2 = typeof(decimal);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(decimal?);
                            }
                            break;
                        case "numeric":
                            text2 = typeof(int);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(int?);
                            }
                            break;
                        case "smallmoney":
                            text2 = typeof(double);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(double?);
                            }
                            break;
                        case "bigint":
                            text2 = typeof(long);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(long?);
                            }
                            break;
                        case "timestamp":
                            text2 = typeof(int);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(int?);
                            }
                            break;
                        case "uniqueidentifier":
                            text2 = typeof(Guid);
                            if (dataRow[2].ToString() == "1")
                            {
                                text2 = typeof(Guid?);
                            }
                            break;
                    }
                    columns.Add(new DataCoulmnDTO()
                    {
                        Name = dataRow[0].ToString(),
                        DisplayName = dataRow[5].ToString(),
                        PropertyType = text2,
                        MaxLength = len,
                    });
                }
                string dateload = "";
                if (columns.Any())
                {
                    var label = "";
                    var input = "";
                    columns.Where(x => !def.Contains(x.Name)).ToList().ForEach(x =>
                    {
                        sb.Append("<div class=\"form-group\">\r\n");
                        if (x.PropertyType == typeof(string))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\"><span style=\"color: red\">*</span>" + x.DisplayName + "</label>\r\n");
                            input = ("            <input type = \"text\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" required value=\"@Model." + x.Name + "\" " + (x.MaxLength != null ? "maxlength=\"" + x.MaxLength + "\"" : "") + " placeholder=\"请输入" + x.DisplayName +
                                      "\" class=\"col-xs-10 col-sm-5\">\r\n");
                        }
                        else if (x.PropertyType == typeof(int))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\"><span style=\"color: red\">*</span>" + x.DisplayName + "</label>\r\n");
                            input = ("            <input type = \"text\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" required digits=\"true\" value=\"@Model." + x.Name + "\" maxlength=\"10\" placeholder=\"请输入" +
                                      x.DisplayName + "\" class=\"col-xs-10 col-sm-5\">\r\n");
                        }
                        else if (x.PropertyType == typeof(int?))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\">" + x.DisplayName + "</label>\r\n");
                            input = ("            <input type = \"text\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" digits=\"true\" value=\"@Model." + x.Name + "\" maxlength=\"10\" placeholder=\"请输入" + x.DisplayName +
                                      "\" class=\"col-xs-10 col-sm-5\">\r\n");
                        }
                        else if (x.PropertyType == typeof(decimal))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\"><span style=\"color: red\">*</span>" + x.DisplayName + "</label>\r\n");
                            input = ("            <input type = \"text\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" required number=\"true\" value=\"@Model." + x.Name + "\" maxlength=\"20\" placeholder=\"请输入" +
                                      x.DisplayName + "\" class=\"col-xs-10 col-sm-5\">\r\n");
                        }
                        else if (x.PropertyType == typeof(decimal?))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\">" + x.DisplayName + "</label>\r\n");
                            input = ("            <input type = \"text\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" number=\"true\" value=\"@Model." + x.Name + "\" maxlength=\"20\" placeholder=\"请输入" + x.DisplayName +
                                      "\" class=\"col-xs-10 col-sm-5\">\r\n");
                        }
                        else if (x.PropertyType == typeof(Guid) || x.PropertyType == typeof(Guid?))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\">" + x.DisplayName + "</label>\r\n");
                            input = ("            <select class=\"input-medium\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" ajax-url=\"/_areaName_/_controller_/获取特定列表\">@*TODO:请改写为对应的ajax请求*@</select>");
                        }
                        else if (x.PropertyType == typeof(DateTime))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\"><span style=\"color: red\">*</span>" + x.DisplayName + "</label>\r\n");
                            input = ("            <input type = \"text\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" required date=\"true\" value=\"@Model." + x.Name + "\" placeholder=\"请输入" +
                                      x.DisplayName + "\" class=\"col-xs-10 col-sm-5\">\r\n");
                            dateload += "$(\"#" + x.Name + "\").datepicker();\r\n";
                        }
                        else if (x.PropertyType == typeof(DateTime?))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\">" + x.DisplayName + "</label>\r\n");
                            input = ("            <input type = \"text\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" date=\"true\" value=\"@Model." + x.Name + "\" placeholder=\"请输入" + x.DisplayName +
                                      "\" class=\"col-xs-10 col-sm-5\">\r\n");
                            dateload += "$(\"#" + x.Name + "\").datepicker();\r\n";
                        }
                        else if (x.PropertyType == typeof(bool) || x.PropertyType == typeof(bool?))
                        {
                            label = ("    <label class=\"col-sm-3 control-label no-padding-right\">" + x.DisplayName + "</label>\r\n");
                            input = ("            <select class=\"input-medium\" id=\"" + x.Name + "\" name=\"" + x.Name +
                                      "\" >@Html.Raw(SelectListItemHelper.LoadBitOption(@Model." + x.Name + ", false))</select>");
                        }

                        //label
                        sb.Append(label);
                        sb.Append("    <div class=\"col-sm-9\">\r\n");
                        sb.Append("        <div class=\"clearfix\">\r\n");
                        //input
                        sb.Append(input);
                        sb.Append("        </div>\r\n");
                        sb.Append("    </div>\r\n");
                        sb.Append("</div>\r\n");
                    });
                }
                dateloads = dateload;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return sb.ToString();
        }

        //生成前端js代码        
        private string LoadcolModelList(DataRowCollection drs)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                var def = new string[] { "ID", "IsDeleted" };
                var columns = new List<DataCoulmnDTO>();

                sb.AppendLine("{ name: 'id', index: 'id', hidden: true },");
                sb.AppendLine("{ id: 'EditOpt', name: '', index: 'id', width: 35, align: 'center', fixed: true, sortable: false, resize: false, formatter: editIcon },");
                foreach (DataRow dataRow in drs)
                {
                    columns.Add(new DataCoulmnDTO()
                    {
                        Name = dataRow[0].ToString(),
                        DisplayName = dataRow[5].ToString(),
                    });
                    
                }
                if (columns.Any())
                {
                    columns.Where(x => !def.Contains(x.Name)).ToList().ForEach(x =>
                    {
                        sb.AppendLine("{ label: '" + x.DisplayName + "', name: '" + x.Name + "', index: '" + x.Name + "' },");
                    });
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return sb.ToString();
        }
        private void label1_Click(object sender, EventArgs e)
        {
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && this.components != null)
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.treeView1 = new System.Windows.Forms.TreeView();
            this.button1 = new System.Windows.Forms.Button();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            // 
            // treeView1
            // 
            this.treeView1.CheckBoxes = true;
            this.treeView1.Location = new System.Drawing.Point(12, 52);
            this.treeView1.Name = "treeView1";
            this.treeView1.Size = new System.Drawing.Size(424, 295);
            this.treeView1.TabIndex = 2;
            this.treeView1.DoubleClick += new System.EventHandler(this.treeView1_DoubleClick);
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(361, 353);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 3;
            this.button1.Text = "生成";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(72, 351);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(182, 21);
            this.textBox1.TabIndex = 4;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 354);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(53, 12);
            this.label1.TabIndex = 5;
            this.label1.Text = "命名空间";
            this.label1.Click += new System.EventHandler(this.label1_Click_2);
            // 
            // checkBox1
            // 
            this.checkBox1.AutoSize = true;
            this.checkBox1.Location = new System.Drawing.Point(261, 353);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(48, 16);
            this.checkBox1.TabIndex = 6;
            this.checkBox1.Text = "异步";
            this.checkBox1.UseVisualStyleBackColor = true;
            // 
            // Form2
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(448, 391);
            this.Controls.Add(this.checkBox1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.treeView1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Form2";
            this.ShowIcon = false;
            this.Text = "生成框架类";
            this.Load += new System.EventHandler(this.Form2_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private bool show = true;

        private void treeView1_DoubleClick(object sender, EventArgs e)
        {
            if (show)
            {
                foreach (TreeNode item in treeView1.Nodes)
                {
                    item.Checked = true;
                }
                show = false;
            }
            else
            {
                foreach (TreeNode item in treeView1.Nodes)
                {
                    item.Checked = false;
                }
                show = true;
            }
        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void label1_Click_2(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }
    }

    public class DataCoulmnDTO
    {
        public string Name { get; set; }
        public string DisplayName { get; set; }
        public Type PropertyType { get; set; }
        public int? MaxLength { get; set; }
    }
}
